package ru.susu.algebra.partition.operation;

import java.util.Arrays;

import ru.susu.algebra.operation.IOperation;
import ru.susu.algebra.partition.Partition;
import ru.susu.algebra.partition.PartitionsFactory;

/**
 * @author akargapolov
 * @since: 03.06.2009
 */
public class CoverPartitionOperation implements IOperation<Partition>
{

	/**
	 * Последний объект - разбиение, перед ним все - целые числа.
	 */
	@Override
	public Partition performOperation(Object... sources)
	{
		Partition result = (Partition) sources[sources.length - 1];

		for (int index = sources.length - 2; index >= 0; index--)
		{
			Integer[] array = result.getArrayRepresentation();
			int m = (Integer)sources[index];
			Integer[] tmp = new Integer[array.length + 1 + m];
			Arrays.fill(tmp, 1);
			for (int i = 0; i < array.length; i++)
				tmp[i + m] += array[i];
			if (array.length != 0)
				tmp[m + array.length] += array[array.length - 1] + m;
			else
				tmp[m + array.length] += m;
			result = PartitionsFactory.createPartition(tmp);
		}

		return result;
	}

}
